package com.aote.rs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;





import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.junit.runner.Runner;
import org.springframework.web.context.ContextLoaderListener;

import com.aote.rs.entity.WxConfig;
import com.aote.rs.entity.WxNofityReturnData;
import com.google.gson.Gson;
import com.sun.research.ws.wadl.Request;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 微信支付成功后交易处理
 */
public class WxPayment {

	static Logger log = Logger.getLogger(WxPayment.class);

	public WxPayment() {

	}

	// 业务处理地址
	private String processUrl;

	public String getProcessUrl() {
		return processUrl;
	}

	public void setProcessUrl(String processUrl) {
		this.processUrl = processUrl;
	}

	@SuppressWarnings("unchecked")
	public String pay(HttpServletRequest request, HttpServletResponse response) {
//		try { 巨鼎天燃气有限公司
		WxConfig wxConfig = (WxConfig) ContextLoaderListener
				.getCurrentWebApplicationContext().getBean("wxConfig");
		String f_filiale = wxConfig.getFiliale();
		// 获取服务器的ip
		String IP = request.getLocalAddr();
		// 获取服务器的端口
		Integer PORT = request.getLocalPort();
			JSONObject data = this.xml(request, response);
			 //保存微信记录,处理交易
			
			log.debug("解析好的数据result:" + data.toString());
			String newdata = "{\"data\":"+data.toString()+"}";
			log.debug("newdata:" + newdata);
			
			//查询用户id--巨鼎，无分公司,一户一表，绑t_userfiles
			//String userid = httpReq(IP,PORT,"wxuserstate", newdata);
			
			//查询用户id--韶关，无分公司,一户多表，绑t_userinfo
			String userid = httpReq(IP,PORT,"sgGetuserinfo", newdata);
			
			// 查询用户id--绵竹 有分公司，一户一表，帮t_userinfo
			// String userid = httpReq(IP,PORT,"Getuserinfo", newdata);
			
			log.debug("userid:" + userid);
			Gson gs = new Gson();
			Map<String,Object> map1 = gs.fromJson(userid, Map.class);
			Map<String,Object> map2 = gs.fromJson(data.toString(), Map.class);
			String f_userid = map1.get("f_userid").toString();
			Double sjbalance =  (Double) map2.get("f_cash_fee")*0.01;
			
			System.out.println("sjbalance" + sjbalance);
	        data.put("f_userid", f_userid);
	        log.debug("加入f_userid的数据result:" + data);
	        
	        // 查询是否有重复的缴费记录--巨鼎和韶关公用这个
			String result = httpReq(IP,PORT,"weixinreturnxml", newdata);
			
			
			
			System.out.println("查到的数据：" +result);
			System.out.println("查到的数据：" +result.isEmpty());
			System.out.println("查到的数据：" +result.length());
			if (result.isEmpty()) {
				//插入缴费记录--巨鼎和韶关公用这个
				httpReq(IP,PORT,"savewxreturnxml", "{\"data\":"+data.toString()+"}");
				
				// 绵竹需要的条件
				//data.put("f_filiale", f_filiale);
				
				
				//获取用户欠费信息--巨鼎
				//String userfee = httpReq(IP,PORT,"userfee", "{\"data\":"+data.toString()+"}");
				
				//获取用户欠费信息--韶关
				String userfee = httpReq(IP,PORT,"sggetuserinfor", "{\"data\":"+data.toString()+"}");
				
				// 获取用户欠费信息--绵竹
				//String userfee = httpReq(IP,PORT,"tygetuserinfor", "{\"data\":"+data.toString()+"}");
				
				System.out.println("用户欠费信息" + userfee);
				JSONObject json = new JSONObject(userfee);
						  
						  
				json.put("f_userid", f_userid);
				json.put("sjbalance", sjbalance);
				
				// 绵竹需要的条件
				//json.put("f_filiale", f_filiale);
				
				
				System.out.println("json:" + json);
				//更新用户欠费信息 
				String newjson = "{\"data\":"+json.toString()+"}";
				System.out.println("newjson:" + newjson);
				
				//httpReq(IP,PORT,"meterfee", newjson); // 巨鼎--无分公司，一户一表，绑t_userfiles
				
				httpReq(IP,PORT,"sgpaygas", newjson); // 韶关--无分公司，一户多表，绑t_userinfo
				
				
				//httpReq(IP,PORT,"typaygas", newjson); // 绵竹--有分公司，一户一表，绑t_userinfo
				
				
			}else{
				return "";
				
			}
			return "";
	}

	public JSONObject xml(@Context HttpServletRequest request,
			@Context HttpServletResponse response) {
		try {
			request.setCharacterEncoding("UTF-8");
			// 读取接收到的xml消息
			InputStream is = request.getInputStream();
			WxNofityReturnData reData = getNofityReturnData(is);
			JSONObject result = new JSONObject();
			result.put("f_return_code", reData.getResult_code());
			result.put("f_return_msg", reData.getReturn_msg());
			result.put("f_appid", reData.getAppid());
			result.put("f_mch_id", reData.getMch_id());
			result.put("f_device_info", reData.getDevice_info());
			result.put("f_nonce_str", reData.getNonce_str());
			result.put("f_sign", reData.getSign());
			result.put("f_result_code", reData.getResult_code());
			result.put("f_err_code", reData.getErr_code());
			result.put("f_err_code_des", reData.getErr_code_des());
			result.put("f_openid", reData.getOpenid());
			result.put("f_is_subscribe", reData.getIs_subscribe());
			result.put("f_trade_type", reData.getTrade_type());
			result.put("f_bank_type", reData.getBank_type());
			result.put("f_total_fee", reData.getTotal_fee());
			result.put("f_fee_type", reData.getFee_type());
			result.put("f_cash_fee", reData.getCash_fee());
			result.put("f_cash_fee_type", reData.getCash_fee_type());
			result.put("f_coupon_fee", reData.getCoupon_fee());
			result.put("f_coupon_count", reData.getCoupon_count());
			result.put("f_coupon_fee_$n", reData.getCoupon_fee_$n());
			result.put("f_coupon_id_$n", reData.getCoupon_id_$n());
			result.put("f_coupon_fee_1", reData.getCoupon_fee_1());
			result.put("f_coupon_id_1", reData.getCoupon_id_1());
			result.put("f_coupon_fee_2", reData.getCoupon_fee_2());
			result.put("f_coupon_id_2", reData.getCoupon_id_2());
			result.put("f_coupon_fee_3", reData.getCoupon_fee_3());
			result.put("f_coupon_id_3", reData.getCoupon_id_3());
			result.put("f_coupon_fee_4", reData.getCoupon_fee_4());
			result.put("f_coupon_id_4", reData.getCoupon_id_4());
			result.put("f_transaction_id", reData.getTransaction_id());
			result.put("f_out_trade_no", reData.getOut_trade_no());
			result.put("f_attach", reData.getAttach());
			result.put("f_time_end", reData.getTime_end());
			return result;
		} catch (Exception e) {
			log.debug("解析回调数据出错" + e.getMessage());
			throw new RuntimeException(e);
		}
	}

	// 转换返回数据
	public WxNofityReturnData getNofityReturnData(InputStream is) {
		try {
			log.debug("解析微信支付回调数据");
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String s = "";
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}
			String xml = sb.toString();
			log.debug("微信支付xml格式数据:" + xml);
			@SuppressWarnings("unused")
			WxNofityReturnData reData = new WxNofityReturnData();
			XStream xs1 = new XStream(new DomDriver());
			xs1.alias("xml", WxNofityReturnData.class);
			
			log.debug("微信支付返回数据:" + (WxNofityReturnData) xs1.fromXML(xml));
			return (WxNofityReturnData) xs1.fromXML(xml);
		} catch (Exception e) {
			log.debug("解析微信支付回调数据出错" + e.getMessage());
			throw new RuntimeException(e);
		}

	}
	private String httpReq(String ip,Integer port, String name, String json) {
		try{
			
			//String path="http://"+ ip +":" + port.toString()+ "/judingwx/rs/logic/"+ URLEncoder.encode(name).replace("+", "%20");//巨鼎
			String path="http://"+ ip +":" + port.toString()+ "/shaoguanwx/rs/logic/"+ URLEncoder.encode(name).replace("+", "%20");//韶关
			//String path="http://"+ ip +":" + port.toString()+ "/weixin/rs/logic/"+ URLEncoder.encode(name).replace("+", "%20");//韶关
			// POSTMethod
			HttpPost postMethod =new HttpPost(path);
			StringEntity se = new StringEntity(json, "UTF-8");
			postMethod.setEntity(se);
			// 发送Post请求
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(postMethod);
			String actual = EntityUtils.toString(response.getEntity(), "UTF8");
			
			return actual;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


}
